/*
 * @Author: wangtao
 * @Date: 2021-03-05 11:47:17
 * @LastEditors: kanglang
 * @LastEditTime: 2021-04-22 14:57:43
 * @Description: 仿elementUI upload
 */
import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  TouchableOpacity,
  NativeModules,
  PixelRatio,
} from 'react-native';
import {
  fontColorDeepGray,
  fontColorSecDeepGray,
  mainBgColorWhite,
  px2dp,
  splitLineColorLightGray,
} from '@/styles';
import { msg } from '@/common';
import { iconCameraGray } from '@/image';
import { uploadImage } from '@/config';

export default class UploadImg extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  static defaultProps = {
    action: 'upload?dirName=all', // 必选参数，上传的地址 请修改dirName
    fileList: [], // 文件列表
    limit: null, // 上传文件上限
  };

  render() {
    const { fileList, limit, style } = this.props;
    return (
      <View style={[styles.container, style]}>
        {/* 已上传 */}
        {this._renderFileList()}
        {/* 上传 */}
        {this._renderAdd()}
      </View>
    );
  }

  // 渲染列表
  _renderFileList = () => {
    const { fileList, onRemove } = this.props;
    return fileList.map((item, index) => {
      return (
        <View style={[styles.addWrap, { marginRight: px2dp(14) }]}>
          <Image
            resizeMode='stretch'
            style={styles.itemImg}
            source={{
              uri: item.imageBase64
                ? `data:image/jpeg;base64,${item.imageBase64}`
                : item.url,
            }}
          />
          <TouchableOpacity
            style={styles.deleteDescWrap}
            activeOpacity={0.8}
            onPress={() => {
              this.onRemove(index);
            }}
          >
            <Text style={styles.deleteDesc}>删除</Text>
          </TouchableOpacity>
        </View>
      );
    });
  };

  // 渲染添加
  _renderAdd = () => {
    const { fileList, limit } = this.props;
    if (limit && fileList.length < limit) {
      return (
        <TouchableOpacity
          onPress={() => {
            this.selectImg();
          }}
          opacity={0.8}
          style={styles.addWrap}
        >
          <Image
            resizeMode='stretch'
            style={styles.addImg}
            source={iconCameraGray}
          />
          <Text style={styles.addDesc}>上传凭证</Text>
          <Text style={styles.addSubDesc}>
            (最多
            {limit}
            张)
          </Text>
        </TouchableOpacity>
      );
    }
    if (!limit) {
      return (
        <TouchableOpacity
          onPress={() => {
            this.selectImg();
          }}
          opacity={0.8}
          style={styles.addWrap}
        >
          <Image
            resizeMode='stretch'
            style={styles.addImg}
            source={iconCameraGray}
          />
          <Text style={styles.addDesc}>上传凭证</Text>
        </TouchableOpacity>
      );
    }
  };

  // 选择照片
  selectImg = () => {
    NativeModules.DataModule.chooseImageOrVideo(
      (path, imageBase64, resType, mimeName) => {
        this.uploadImage(path, imageBase64, resType, mimeName);
      },
    );
  };

  onRemove = (index) => {
    let { fileList, onChange } = this.props;
    fileList.splice(index, 1);
    onChange(fileList);
  };

  // 上传照片
  uploadImage(path, imageBase64, resType, mimeName) {
    let { fileList, onChange, action } = this.props;
    uploadImage(action, path)
      .then((res) => {
        // 请求成功
        if (res.success) {
          const { url, localFileName } = res.data;
          fileList.push({ name: localFileName, url, imageBase64 });
          onChange(fileList);
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      })
      .catch((err) => {
        // 请求失败
        msg.emit('app:tip', { text: '上传出错，请重试' });
      });
  }
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    // backgroundColor:'pink',
    flexDirection: 'row',
  },
  addWrap: {
    width: px2dp(152),
    height: px2dp(152),
    borderColor: splitLineColorLightGray,
    borderWidth: 1 / PixelRatio.get(),
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(8),
    overflow: 'hidden',
  },

  addImg: {
    width: px2dp(40),
    height: px2dp(40),
  },
  addDesc: {
    fontSize: px2dp(24),
    color: fontColorDeepGray,
  },
  addSubDesc: {
    fontSize: px2dp(22),
    color: fontColorSecDeepGray,
  },

  itemImg: {
    width: '100%',
    height: '100%',
  },
  deleteDescWrap: {
    width: '100%',
    height: px2dp(44),
    backgroundColor: 'rgba(0,0,0,0.5)',
    position: 'absolute',
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center',
  },
  deleteDesc: {
    fontSize: px2dp(24),
    color: mainBgColorWhite,
  },
});
